package androidx.lifecycle

import android.util.Log
import androidx.annotation.MainThread

/**
 * 依赖于androidx.lifecycle.LiveData 的bus  https://blog.csdn.net/weixin_41648633/article/details/149610015?spm=1001.2014.3001.5501
 * 用于页面之间通信
 */
object AndroidLiveDataBus {
    private val bus = mutableMapOf<String, BusMutableLiveData<Any>>()

    fun <T> with(key: String): BusMutableLiveData<T> {
        if (!bus.contains(key)) {
            bus[key] = BusMutableLiveData()
        }
        return bus[key] as BusMutableLiveData<T>
    }

    fun msgObserver(key: String,owner: LifecycleOwner, observer: Observer<Any>){
        val busMutableLiveData =
        if (!bus.contains(key)) {
            bus[key] = BusMutableLiveData()
            bus[key]
        }else{
            bus[key]
        }
        busMutableLiveData?.let {
            val observerWrapper = ObserverWrapper(observer)
            Log.i("zq_demo","it.version>>${it.version}  START_VERSION>>${BusMutableLiveData.START_VERSION}")
            observerWrapper.nextEvent = it.version > BusMutableLiveData.START_VERSION
            it.observe(owner,observerWrapper)
        }
    }

    fun msgStickObserver(key: String,owner: LifecycleOwner, observer: Observer<Any>){
        val busMutableLiveData =
            if (!bus.contains(key)) {
                bus[key] = BusMutableLiveData()
                bus[key]
            }else{
                bus[key]
            }
        busMutableLiveData?.let {
            val observerWrapper = ObserverWrapper(observer)
            it.observe(owner,observerWrapper)
        }
    }
}

open class BusMutableLiveData<T>:MutableLiveData<T>(){
    companion object{
        const val START_VERSION = LiveData.START_VERSION
    }

    public override fun getVersion(): Int {
        return super.getVersion()
    }

    @MainThread
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        assertMainThread("observe")
        if (owner.lifecycle.currentState == Lifecycle.State.DESTROYED) {
            // ignore
            return
        }
        try{
            val wrapper = LifecycleBoundObserver(owner, observer) //这个是ObserverWrapper  需要更改其mLastVersion

            val liveData = LiveData::class.java
            val mObserversField = liveData.getDeclaredField("mObservers") //     private SafeIterableMap<Observer<? super T>, ObserverWrapper> mObservers = new SafeIterableMap<>();  放observer的map
            mObserversField.isAccessible = true

            //获取当前LiveData实例的mObservers映射
            val mObservers = mObserversField.get(this)
            val putIfAbsent = mObservers.javaClass.getDeclaredMethod("putIfAbsent", Any::class.java,Any::class.java)
            putIfAbsent.isAccessible = true
            val existing = putIfAbsent.invoke(mObservers,observer,wrapper) as? LiveData<*>.LifecycleBoundObserver
            require(!(existing != null && !existing.isAttachedTo(owner))) {
                ("Cannot add the same observer"
                        + " with different lifecycles")
            }
            if (existing != null) {
                return
            }
            owner.lifecycle.addObserver(wrapper)
        }catch (e:Exception){
            Log.i("zq_demo","e>>${e}")
        }
    }
}

class ObserverWrapper<T>(val observer: Observer<T>,var nextEvent:Boolean = false):Observer<T>{
    override fun onChanged(value: T) {

        Log.i("zq_demo","nextEvent》》${nextEvent}")

        if(nextEvent){
            nextEvent = false
            return
        }
        observer.onChanged(value)
    }
}

